package cn.cj.erp.common.security.security.config;

import cn.cj.erp.common.utils.encrypt.EncryptUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Sm3密码加密其
 *
 * @author chenjian
 */
@Slf4j
public class Sm3PasswordEncoder implements PasswordEncoder {
    /** 
     * 加密
     * @param rawPassword 明文密码
     * @return java.lang.String
     */
    @Override
    public String encode(CharSequence rawPassword) {
        if (StrUtil.isEmpty(rawPassword)) {
            log.info("Sm3PasswordEncoder encode结束，rawPassword为空，异常退出");
            throw new IllegalArgumentException("密码不能为空");
        }
        return EncryptUtil.passwordEncrypt(rawPassword.toString());
    }

    /**
     * 匹配，第一个是客户端的明文密码，第二个是已经加密的密码
     * @param rawPassword 明文密码
     * @param encodedPassword 已经加密的密码
     * @return boolean
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (StrUtil.isEmpty(rawPassword)) {
            log.info("Sm3PasswordEncoder matches rawPassword ={}, encodedPassword={}: rawPassword为空", rawPassword, encodedPassword);
            throw new IllegalArgumentException("密码为空");
        }
        if (StrUtil.isEmpty(encodedPassword)) {
            log.info("Sm3PasswordEncoder matches rawPassword ={}, encodedPassword={}: encodedPassword为空", rawPassword, encodedPassword);
            return false;
        }
        return StrUtil.equals(encodedPassword, EncryptUtil.passwordEncrypt(rawPassword.toString()));
    }
}
